<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="样品编号" prop="sampleName">
        <el-input
            v-model="queryParams.sampleName"
            placeholder="请输入样品编号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="送样日期" prop="deliveryDate">
        <el-date-picker
            v-model="queryParams.deliveryDate"
            type="date"
            placeholder="Pick a day"
            :size="'default'"
            value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
      <el-form-item style="position: absolute;right: 0">
        <el-button
            type="success"
            plain
            @click="back"
        >返回</el-button>
      </el-form-item>
    </el-form>
    <el-row>
      <el-col :span="2" v-if="finish==0">
        <el-button
            type="primary"
            plain
            @click="callForSample"
        >申请流转</el-button>
      </el-col>
      <el-col :span="2" v-if="finish==0">
        <el-button
            type="primary"
            plain
            icon="Refresh"
            :disabled="!canDo"
            @click="flume"
        >流转
        </el-button>
      </el-col>
      <el-col :span="2" v-if="finish==0">
        <el-button
            type="primary"
            plain
            icon="Refresh"
            :disabled="!canDo"
            @click="toAddExps"
        >添加实验
        </el-button>
      </el-col>
      <el-col :span="2">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
        >导出
        </el-button>
      </el-col>
    </el-row>
    <el-table v-loading="loading" :data="sampleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column fixed label="样品编号" align="center" width="100" prop="sampleName" />
      <el-table-column v-if="finish==0" label="图片" align="center" prop="sampleImage" width="120">
        <template #default="scope">
          <el-image
              v-if="scope.row.sampleImage"
              style="width: 100px; height: 100px"
              :src="scope.row.sampleImage.split(';')[0]"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :preview-src-list="scope.row.sampleImage.slice(0,-1).split(';')"
              :initial-index="4"
              fit="cover"
              preview-teleported
          />
        </template>
      </el-table-column>
      <el-table-column v-if="finish==0" label="状态" align="center" width="70" prop="sampleStatus" >
        <template #default="scope">
          <div v-if="scope.row.sampleStatus<2" style="background-color: blue;color: white;border-radius: 30%;font-size: 12px">
            在库
          </div>
          <div v-else style="background-color: lawngreen;color: white;border-radius: 30%;font-size: 12px">
            出库
          </div>
        </template>
      </el-table-column>
      <el-table-column v-if="finish==0" label="申请状态" width="100">
        <template #default="scope">
          <div v-if="scope.row.sampleStatus==1" style="background-color: #4abd4c;color: white;font-size: 12px;border-radius: 30%;text-align: center" >
            已申请
          </div>
          <div v-if="scope.row.sampleStatus<1" style="background-color: #4AB7BD;color: white;font-size: 12px;border-radius: 30%;text-align: center" >
            未申请
          </div>
        </template>
      </el-table-column>
      <el-table-column v-if="finish==0" label="实验状态" width="180" align="center">
        <template #default="scope">
          <div v-if="scope.row.expeNum==0"
               style="background-color: #4488e0;color: white;font-size: 12px;border-radius: 30%;text-align: center;padding: 2px 5px;display: inline-block" >
            未添加实验
          </div>
          <div v-else-if="scope.row.expeNum==1 && scope.row.hasFlumExpeNum==0" style="background-color: #1ad029;color: white;font-size: 12px;padding: 2px 5px;border-radius: 30%;text-align: center;display: inline-block" >
            已添加实验
          </div>
          <div v-else style="background-color: #1ad029;color: white;font-size: 12px;padding: 2px 5px;border-radius: 30%;text-align: center;display: inline-block" >
            已流转
          </div>
        </template>
      </el-table-column>
      <el-table-column v-if="finish==0" label="井号" align="center" width="100" prop="wellId" />
      <el-table-column v-if="finish==0" label="深度(m)" align="center" width="100" prop="depth" />
      <el-table-column v-if="finish==0" label="岩石类型" align="center" width="200" prop="rockType" />
      <el-table-column v-if="finish==0" label="样品量(g)" align="center" width="120" prop="sampleQuantity" />
      <el-table-column v-if="finish==0" label="样品尺寸(cm)" align="center" width="150" prop="sampleSize" />
      <el-table-column label="实验类型" align="center" width="150" prop="type" />
      <el-table-column label="实验操作人" align="center" width="150" prop="experimentPerson" />
      <el-table-column label="实验数量" align="center" width="150" prop="experimentNumber" />
      <el-table-column label="实验单价" align="center" width="150" prop="experimentPrice" >
        <template #default="scope">
          {{scope.row.experimentPrice/100}}
        </template>
      </el-table-column>
      <el-table-column v-if="finish==1" label="开始日期" align="center" width="160" prop="experimentDate" />
      <el-table-column v-if="finish==1" label="结束日期" align="center" width="160" prop="experimentEndDate" />
      <el-table-column v-if="post==1" label="岗位名称" align="center" width="160" prop="job" />
      <el-table-column v-if="post==1" label="岗位价格" align="center" width="160" prop="jobPrice" />
      <el-table-column label="实验备注" align="center" width="150" prop="experimentRemark" />
      <el-table-column fixed="right" label="操作" width="200" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <div v-if="scope.row.confirmStatus==0">
            <el-button v-if="finish==0" link type="primary" icon="Edit" @click="toAddExperiment(scope.row.sampleId,scope.row.sampleStatus)">添加实验</el-button>
            <el-button v-if="finish==0" link type="primary" icon="Edit" @click="toChangeExperiment(scope.row.sampleId)">取消实验</el-button>
          </div>
          <div v-else>
            <el-button v-if="finish==0 && scope.row.sampleStatus==2" link type="success" icon="Edit" @click="handleConfirm(scope.row.sampleId,scope.row.confirmStatus)">确认</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />


    <!--  流转对话框  -->
    <el-dialog :title="title" v-model="flumeView" width="600px" append-to-body>
      <el-form :model="lzform" label-width="100px">
        <el-form-item label="流转到">
          <el-select
              v-model="lzform.postId"
              filterable
              placeholder="Select"
              style="width: 240px;max-height: 100px"
          >
            <el-option key="2" label="实验分发人" value="7"/>
            <el-option key="3" label="项目负责人" value="8"/>
          </el-select>
        </el-form-item>
        <el-form-item label="流转意见">
          <el-input
              v-model="lzform.circulationSuggestion"
              type="textarea"
              :rows="3"
              placeholder="请输入流转意见"/>
        </el-form-item>
        <el-form-item style="text-align: center">
          <el-button type="success" @click="submitFlume()" >确定</el-button>
          <el-button type="danger" @click="flume()">关闭</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 添加或修改实验细节管理对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="detailRef" :model="form" :rules="rules" label-width="100px">
        <!--        <el-form-item label="样品编号" prop="sampleId">-->
        <!--          <el-input v-model="form.sampleId" disabled style="width: 150px"/>-->
        <!--        </el-form-item>-->
        <el-form-item label="实验类型" prop="typeId">
          <el-select
              v-model="form.typeId"
              filterable
              placeholder="Select"
              style="width: 240px;max-height: 100px"
          >
            <el-option
                v-for="item in options"
                :key="item.typeId"
                :label="item.typeName"
                :value="item.typeId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="数量" prop="experimentNumber">
          <el-input v-model="form.experimentNumber" placeholder="请输入数量"/>
        </el-form-item>
        <el-form-item label="单价" prop="experimentPrice">
          <el-input v-model="form.experimentPrice" placeholder="请输入单价"/>
        </el-form-item>
        <el-form-item label="总价">
          <el-input v-model="sum" disabled/>
        </el-form-item>
        <el-form-item label="实验备注" prop="experimentRemark">
          <el-input v-model="form.experimentRemark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Sample">
import {useRoute} from "vue-router";
import router from "@/router/index.js";
import {
  addDetail,
  callSamples, delDetail, getExperimentBySampleId,
  getNoFlumeExperiments,
  getNoFlumeProjects, getSampleById, listAllExperiment,
  listSample,
  postFlume, updateDetail
} from "@/api/experiment/experiment.js";
import {ElMessage, ElMessageBox, ElNotification} from "element-plus";
import {Cconfirm} from "@/api/sample/sample.js";
import BigNumber from "bignumber.js";

const route=useRoute();
const itemId=ref(route.query.id);
const finish=route.query.finish;
const post=route.query.post;

const { proxy } = getCurrentInstance();

const sampleList = ref([]);
const loading = ref(false);//默认应为true
const showSearch = ref(true);
const sampleIds = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const selectSample=ref([]);

const data = reactive({
  form: {
    experimentId: null,
    typeId: null,
    sampleId: null,
    experimentName: null,
    experimentNumber: 0,
    experimentPrice: 0,
    jobId: null,
    jobPrice: null,
    experimentDate: null,
    experimentRemark: null,
    expermentType: null
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    sampleId: null,
    deliveryDate: null,
    projectId:itemId.value
  },
  rules: {
    typeId: [
      { required: true, message: '请选择实验类型', trigger: 'blur' }
    ],
    experimentNumber: [
      { required: true, message: '请填写实验数量', trigger: 'blur' }
    ],
    experimentPrice: [
      { required: true, message: '请填写实验单价', trigger: 'blur' }
    ],
  },
  lzform:{
    sampleId: 20
  },
});

const {queryParams, form, rules,lzform} = toRefs(data);
getList();

/** 流转按钮  */
const flumeView = ref(false)

function flume() {
  flumeView.value = !flumeView.value;
}

function submitFlume(){
  if (sampleIds.value.length==0){
    ElMessage({
      message:'请选择至少一项实验流转',
      type:'warning'
    })
    flume();
    return;
  }
  if (lzform.value.postId==null){
    ElMessage({
      message:'请选择流转去向',
      type:'warning'
    })
    return;
  }
  for (let i = 0; i < sampleIds.value.length; i++) {
    if (selectSample.value[i].sampleStatus<2){
      ElMessage({
        message:'请先将样品出库',
        type:'warning'
      })
      return;
    }
    if (selectSample.value[i].expeNum==0){
      ElMessage({
        message:'请先添加实验',
        type:'warning'
      })
      return;
    }
  }
  if(lzform.value.postId==7){
    getNoFlumeExperiments({ids: sampleIds.value}).then(res=>{
      lzform.value.ids=res.data;
      if(lzform.value.ids.length == 0){
        ElMessage({
          message:'样品已全部流转',
          type:'warning'
        })
        return;
      }
      postFlume(lzform.value).then(res=>{
        ElMessageBox.alert('流转成功','提示',{
          confirmButtonText: 'OK',
          callback:(value, action)=>{
            flume();
            reset();
          }
        })
        getList();
      })
    })
  }
  if(lzform.value.postId==8){
    getNoFlumeProjects({ids: sampleIds.value}).then(res=>{
      lzform.value.ids=res.data;
      if(lzform.value.ids.length == 0){
        ElMessage({
          message:'样品已全部流转',
          type:'warning'
        })
        return;
      }
      postFlume(lzform.value).then(res=>{
        ElMessageBox.alert('流转成功','提示',{
          confirmButtonText: 'OK',
          callback:(value, action)=>{
            flume();
            reset();
          }
        })
        getList();
      })
    })
  }
}

/** 查询样品列表 */
function getList() {
  loading.value = true;
  queryParams.value.finish=finish;
  listSample(queryParams.value).then(response => {
    sampleList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
// 表单重置
function reset() {
  form.value = {
    experimentId: null,
    typeId: null,
    sampleId: null,
    experimentName: null,
    experimentNumber: 0,
    experimentPrice: 0,
    jobId: null,
    jobPrice: null,
    experimentDate: null,
    experimentRemark: null,
    expermentType: null
  };
  lzform.value={
    postId:null,
    circulationSuggestion:null
  }
  proxy.resetForm("detailRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/**  申请流转按钮  */
function callForSample(){
  if (selectSample.value.length<1){
    ElMessage({
      message: '请至少选择一项样品！',
      type: 'warning',
    })
    return;
  }
  for (let value of selectSample.value) {
    if (value.sampleStatus>1){
      ElMessage({
        message:'样品已出库，不可重复申请',
        type:'warning'
      })
      return;
    }
  }
  callSamples(selectSample.value).then(res=>{
    if (res.code==200){
      ElMessage({
        message: '成功申请流转！',
        type: 'success',
      })
      getList();
    }
  })
}
function handleSelectionChange(selection){
  sampleIds.value = selection.map(item => item.sampleId);
  selectSample.value=[]
  for (let e of selection) {
    selectSample.value.push({projectId:Number(route.query.id),sampleId:e.sampleId,sampleStatus:e.sampleStatus,sampleName:e.sampleName,expeNum:e.expeNum})
  }
  canDo.value=true;
  for (let e of selection) {
    if (e.confirmStatus!=0 && e.confirmStatus!=16 && e.confirmStatus!=8){
      canDo.value=false;
      break;
    }
  }
}
//添加实验操作

const open = ref(false);

let f=true;
let adds=false;
function toAddExps(){
  let ids=[];
  ids=sampleIds.value.concat();
  if (ids.length==0)
    return;
  reset();
  checkSample(ids);
}

function checkSample(ids){
  if (ids==null || ids.length==0){
    adds=true;
    form.value={};
    open.value=true;
    return;
  }
  let id = ids.pop();
  getSampleById(id).then(res=>{
    let status=res.data.sampleStatus;
    if (status<2){
      f=false;
      ElMessage({
        message:'添加失败，请先将样品流转至实验管理员！',
        type:"warning"
      })
      return;
    }else if (status>2){
      f=false;
      ElMessage({
        message:'添加失败，样品已流转！',
        type:"warning"
      })
      return;
    }
    getExperimentBySampleId(id).then(res=>{
      if (res.data!=null){
        f=false;
        ElMessage({
          message:'添加失败，样品已添加实验！',
          type:"warning"
        })
      }else {
        checkSample(ids);
      }
    })
  })
}

function toAddExperiment(sampleId,sampleStatus){
  adds=false;
  getSampleById(sampleId).then(res=>{
    reset();
    let status=res.data.sampleStatus;
    if (status<2){
      ElMessage({
        message:'添加失败，请先将样品流转至实验管理员！',
        type:"warning"
      })
      return;
    }else if (status>2){
      ElMessage({
        message:'添加失败，样品已流转！',
        type:"warning"
      })
      return;
    }
    getExperimentBySampleId(sampleId).then(res=>{
      if (res.data==null){
        form.value={};
        form.value.sampleId=sampleId;
      }else{
        res.data.experimentPrice=res.data.experimentPrice/100
        form.value=res.data;
      }
      open.value=true;
    })
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["detailRef"].validate(valid => {
    if (valid) {
      form.value.experimentPrice=new BigNumber(form.value.experimentPrice).times(100).toNumber();
      if (adds==true){
        form.value.sampleIds=sampleIds.value;
        addDetail(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }else{
        if (form.value.experimentId != null) {
          updateDetail(form.value).then(response => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
          });
        } else {
          addDetail(form.value).then(response => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
          });
        }
      }
    }
  });
}
function cancel(){
  open.value=false;
}


function toChangeExperiment(sampleId){
  getExperimentBySampleId(sampleId).then(res=>{
    if (res.data==null){
      ElMessage({message:'删除失败，请先添加实验！',type:'warning'})
      return;
    }
    getSampleById(sampleId).then(res=> {
      let status = res.data.sampleStatus;
      if (status>2){
        ElMessage({message:'删除失败，样品已流转！',type:'warning'})
        return;
      }
      ElMessageBox.confirm(
          '确定要删除该实验吗？',
          '警告',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }).then(() => {
        delDetail(sampleId);
        getList();
      })
    })
  })
}
const sum = ref();
const watchExperimentPrice = watch(form, () => {
  sum.value =  new BigNumber(form.value.experimentPrice).times(form.value.experimentNumber).toNumber();
}, {deep: true})
/** 获取所有实验 */
const options=ref();
function getAllexperiment() {
  listAllExperiment().then(res => {
    options.value = res.rows;
  })
}


function back(){
  router.back();
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('/experiment/experiment/sample/export', {...queryParams.value}, `experiment_${new Date().getTime()}.xlsx`)
}
/** 确认 */
//确认状态
const canDo=ref(true);

function handleConfirm(id,status){
  Cconfirm(id).then(res=>{
    if (res.data){
      ElNotification({title:'提示',type:'success',message:'确认成功'})
      getList();
    }
  })
}

getAllexperiment();
</script>
